package com.transmit.conf.propertis;

import com.alibaba.fastjson.JSONObject;
import com.transmit.util.BASE64;
import com.transmit.util.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTokenProperty implements TokenManager {

    @Value("${token.expires}")
    Long TOKEN_EXPIRES_HOUR;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public UserToken searchToken(HttpServletRequest req) {
        UserToken userToken = null;
        if (req.getHeader("token") != null) {
            try {
//                userToken = JSONObject.parseObject(req.getHeader("token"), UserToken.class);
                userToken = new UserToken();
                userToken.setToken(req.getHeader("token"));
            } catch (Exception e) {
                return null;
            }
            return userToken;
        }

        if (req.getCookies() != null) {
            for (Cookie cookie : req.getCookies()) {
                if (cookie.getName().equals("token")) {
                    try {
                        userToken = JSONObject.parseObject(BASE64.decryptBASE64(cookie.getValue()), UserToken.class);
                        return userToken;
                    } catch (Exception e) {
                        return null;
                    }
                }
            }
        }

        if (req.getQueryString() != null) {
//            Map m = HttpUtil.getQueryParams(req);
//            if (m.containsKey("t")) {
//                userToken = JSONObject.parseObject(BASE64.decryptBASE64(m.get("t").toString()), UserToken.class);
//            }
//            return userToken;
        }

        return userToken;
    }


    @Override
    public UserToken createToken(String username) {
        //使用uuid作为源token
        String token = UUID.randomUUID().toString().replace("-", "");
        UserToken model = new UserToken(username, token);

        //存储到redis并设置过期时间
        redisTemplate.boundValueOps(token).set(username + "", TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return model;
    }


    @Override
    public UserToken getToken(String authentication) {
        if (authentication == null || authentication.length() == 0) {
            return null;
        }
        String[] param = authentication.split("_");
        if (param.length != 2) {
            return null;
        }
        //使用userId和源token简单拼接成的token，可以增加加密措施
        String username = param[0];
        String token = param[1];
        return new UserToken(username, token);
    }


    @Override
    public boolean checkToken(UserToken model) {
        if (model == null) {
            return false;
        }
        Object userid = redisTemplate.boundValueOps(model.getToken()).get();

//        if (userid == null || !userid.equals(model.getUsername().toString())) {
        if (userid == null) {
            return false;
        }
        //如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
//        redisTemplate.boundValueOps(model.getUsername()).expire(TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        redisTemplate.boundValueOps(model.getToken()).expire(TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return true;
    }


    @Override
    public void deleteToken(String token) {
        redisTemplate.delete(token);
    }
}